package filter;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("请求被登录过滤器拦截！");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        if (session.getAttribute("user") == null) {//如果session新创建的，则表示这个用户还没有登录，是刚开始访问的//
            String msg = "您还没有登录呢！三秒后自动跳转到登录页面！";
            response.getWriter().write(msg);
            response.setHeader("Refresh", "3;URL=/login.html");//
        } else {
            filterChain.doFilter(request, response);
        }
        Cookie cookie = new Cookie("JSESSIONID", session.getId());
        response.addCookie(cookie);
    }

    @Override
    public void destroy() {

    }
}
